<?php
require_once __DIR__.'/../includes/auth.php';
header('Content-Type: application/json');

$q = $_GET['q'] ?? '';
$results = [];

if (strlen($q) > 2) {
    try {
        $stmt = $pdo->prepare("
            SELECT 'ship' AS type, id, name_zh, imo_number 
            FROM ships WHERE name_zh LIKE ? OR imo_number = ?
            UNION
            SELECT 'port' AS type, id, name_zh, code 
            FROM ports WHERE name_zh LIKE ? OR code = ?
            LIMIT 20
        ");
        $searchTerm = "%$q%";
        $stmt->execute([$searchTerm, $q, $searchTerm, $q]);
        $results = $stmt->fetchAll();
    } catch (Exception $e) {
        http_response_code(500);
        die(json_encode(['error' => '搜索服务暂不可用']));
    }
}

echo json_encode($results);